<template>
  <div class="app-container">
    <!-- 标题部分 -->
    <div class="page-header">
      <div class="header-title">
        <i class="el-icon-shopping-cart-full"></i>
        <span>商品采购中心</span>
        <span v-if="$route.query.categoryType" class="category-tag">
          {{ getCategoryTypeName($route.query.categoryType) }}
        </span>
      </div>
      <div class="header-desc">浏览并选择您需要的商品，快速下单采购</div>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入商品名称"
            clearable
            prefix-icon="el-icon-goods"
            tabindex="1"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="供应商" prop="supplierId">
          <div class="custom-select-wrapper" ref="supplierSelect">
            <div class="custom-select" @click="toggleSupplierDropdown">
              <div class="selected-value">
                {{ getSelectedSupplierName() || '请选择供应商' }}
              </div>
              <i v-if="queryParams.supplierId" class="el-icon-close clear-icon" @click.stop="clearSupplier"></i>
              <i class="el-icon-arrow-down" :class="{ 'is-open': showSupplierDropdown }"></i>
            </div>
          </div>
          <!-- 将下拉框内容放在body下，确保正确显示在最顶层 -->
          <teleport to="body">
            <div
              v-show="showSupplierDropdown"
              class="custom-options"
              :style="dropdownStyle"
            >
              <div class="custom-options-wrapper">
                <div
                  v-for="item in supplierList"
                  :key="item.id"
                  class="custom-option"
                  :class="{ 'is-selected': item.id === queryParams.supplierId }"
                  @click="selectSupplier(item)"
                >
                  <span>{{ item.name }}</span>
                  <span v-if="item.role" class="option-role">{{ item.role }}</span>
                </div>
                <div v-if="supplierList.length === 0" class="no-data">
                  <i class="el-icon-loading" v-if="loadingSuppliers"></i>
                  <span v-else>暂无数据</span>
                </div>
              </div>
            </div>
          </teleport>
        </el-form-item>

        <el-form-item label="商品类型" prop="type">
          <el-cascader
            v-if="isDataLoaded"
            ref="typeCascader"
            v-model="queryParams.type"
            :options="typeTreeData"
            :props="{
              checkStrictly: true,
              value: 'id',
              label: 'name',
              children: 'children',
              emitPath: false,
              expandTrigger: 'hover'
            }"
            placeholder="请选择商品类型"
            clearable
            :automatic-dropdown="false"
            tabindex="-1"
            @change="val => console.log('选择的类型ID:', val)"
          ></el-cascader>
          <div v-else class="cascader-placeholder">请选择商品类型</div>
        </el-form-item>

        <el-form-item label="供应商类型" prop="roleName" label-width="90px">
          <div class="custom-select-wrapper" ref="roleNameSelect">
            <div class="custom-select" @click="toggleRoleNameDropdown">
              <div class="selected-value">
                {{ getSelectedRoleName() || '请选择供应商类型' }}
              </div>
              <i v-if="queryParams.roleName" class="el-icon-close clear-icon" @click.stop="clearRoleName"></i>
              <i class="el-icon-arrow-down" :class="{ 'is-open': showRoleNameDropdown }"></i>
            </div>
          </div>
          <!-- 将下拉框内容放在body下，确保正确显示在最顶层 -->
          <teleport to="body">
            <div
              v-show="showRoleNameDropdown"
              class="custom-options"
              :style="roleNameDropdownStyle"
              :automatic-dropdown="false"
            >
              <div class="custom-options-wrapper">
                <div
                  v-for="item in roleNameList"
                  :key="item.value"
                  class="custom-option"
                  :class="{ 'is-selected': item.value === queryParams.roleName }"
                  @click="selectRoleName(item)"
                >
                  <span>{{ item.label }}</span>
                </div>
                <div v-if="roleNameList.length === 0" class="no-data">
                  <span>暂无数据</span>
                </div>
              </div>
            </div>
          </teleport>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品列表展示 -->
    <el-card class="product-list-card" v-loading="loading">
      <div slot="header" class="card-header">
        <span>商品列表</span>
        <div class="header-actions">
          <el-dropdown>
            <el-button type="text" icon="el-icon-sort">
              排序方式<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>价格从低到高</el-dropdown-item>
              <el-dropdown-item>价格从高到低</el-dropdown-item>
              <el-dropdown-item>最新上架</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>

      <div class="products-container">
        <el-row :gutter="20">
          <el-col
            :xs="12"
            :sm="8"
            :md="6"
            :lg="4"
            :xl="4"
            v-for="item in productListList"
            :key="item.id"
            class="product-col"
          >
            <div class="product-card" @click="viewProduct(item)">
              <div class="product-image">
                <img
                  :src="getProductImage(item)"
                  :onerror="handleImageError"
                  alt="商品图片"
                />
                <div class="product-tags">
                  <el-tag size="mini" type="success" v-if="item.stockQuantity > 10">库存充足:{{item.stockQuantity}}</el-tag>
                  <el-tag size="mini" type="warning" v-else-if="item.stockQuantity > 0">库存紧张:{{item.stockQuantity}}</el-tag>
                  <el-tag size="mini" type="danger" v-else>缺货</el-tag>
                </div>
              </div>
              <div class="product-info">
                <div class="product-title" :title="item.name">{{ item.name }}</div>
                <div class="product-meta">
                  <span class="product-type" v-if="item.type" :title="getTypeName(item.type)">
                    {{ getTypeName(item.type) }}
                  </span>
                  <span class="product-supplier" v-if="item.brand" :title="item.brand">{{ item.brand }}</span>
                </div>
                <div class="bottom-info">
                  <span class="product-price">¥{{ item.unitPrice }}</span>
                  <el-button v-if="!isCurrentUserSupplier(item)" type="primary" size="mini" icon="el-icon-shopping-cart-1" circle @click.stop="addToCart(item)"></el-button>
                  <el-button v-else type="info" size="mini" icon="el-icon-shopping-cart-1" circle disabled></el-button>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- 无数据提示 -->
        <div class="empty-block" v-if="!loading && productListList.length === 0">
          <i class="el-icon-goods"></i>
          <span>暂无商品数据</span>
          <el-button type="primary" size="small" @click="handleQuery">刷新</el-button>
        </div>
      </div>

      <!-- 分页器 -->
      <div class="pagination-container">
        <pagination
          v-show="total > 0"
          :total="total"
          :page-sizes="[12, 20, 30, 40]"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="handlePagination"
        />
      </div>
    </el-card>

    <!-- 购物车弹出组件 -->
    <cart-popup
      :value="showCart"
      :cartItem="cartItem"
      :quantity.sync="purchaseQuantity"
      @input="showCart = $event"
    />
  </div>
</template>

<script>
import { listProdinfo } from "@/api/supply/prodinfo";
import defaultImage from '@/assets/images/product1.jpg'; // 导入默认图片
import { fetchCategoryTree } from "@/api/official";
import request from '@/utils/request'; // 添加到文件顶部的导入区域
import CartPopup from './CartPopup.vue';

export default {
  name: "ProductList",
  dicts: ['product_type', 'product_status'],
  components: {
    CartPopup
  },
  data() {
    return {
      isDataLoaded: false, // 控制下拉框渲染时机
      preventAutoRender: true, // 防止初次自动渲染
      loading: true,
      showSearch: true,
      total: 0,
      productListList: [],
      defaultImage: defaultImage, // 添加默认图片
      handleImageError: 'this.src="' + defaultImage + '"', // 图片加载失败时的处理
      //供应商数据
      supplierList: [],
      // 商品类型树数据
      typeTreeData: [],
      // 第三级商品类型列表
      thirdLevelTypes: [],
      queryParams: {
        pageNum: 1,
        pageSize: 12,
        name: null,
        type: null,
        status: 1,
        supplierId: undefined, // 使用undefined，避免null触发展开
        supplierName: null,
        roleName: null
      },
      // 购物车相关数据
      showCart: false,
      cartItem: {},
      purchaseQuantity: 1,
      showSupplierDropdown: false, // 控制供应商下拉框显示
      loadingSuppliers: false, // 控制供应商加载状态
      dropdownStyle: {
        position: 'fixed',
        top: '0px',
        left: '0px',
        minWidth: '200px',
        zIndex: 2000
      },
      roleNameList: [
        { value: '首选供应商', label: '首选供应商' },
        { value: '战略供应商', label: '战略供应商' },
        { value: '合格供应商', label: '合格供应商' }
      ],
      showRoleNameDropdown: false, // 控制供应商类型下拉框显示
      roleNameDropdownStyle: {
        position: 'fixed',
        top: '0px',
        left: '0px',
        minWidth: '200px',
        zIndex: 2000
      },
    };
  },
  created() {
    this.loading = true;

    // 从路由参数中获取分类类型
    const { categoryType } = this.$route.query;
    
    // 从sessionStorage中获取搜索关键词，如果有则设置到查询参数中并清除存储
    const searchKeyword = sessionStorage.getItem('search_keyword');
    if (searchKeyword) {
      this.queryParams.name = searchKeyword;
      // 使用完关键词后立即清除，避免刷新页面时重复使用
      sessionStorage.removeItem('search_keyword');
    }
    
    // 从sessionStorage中获取分类ID，如果有则设置到查询参数中并清除存储
    const categoryId = sessionStorage.getItem('category_id');
    if (categoryId) {
      this.queryParams.type = categoryId;
      console.log("从分类导航获取的分类ID:", categoryId);
      // 使用完分类ID后立即清除，避免刷新页面时重复使用
      sessionStorage.removeItem('category_id');
    }
    
    if (categoryType) {
      console.log("当前查看的商品类别:", categoryType);

      // 根据不同类型设置对应的查询条件
      if (categoryType === 'strategic') {
        // 战略商品区 - 筛选战略供应商类型的商品
        this.queryParams.roleName = '供应商-战略合作商';
      } else if (categoryType === 'selfOperated') {
        // 自营商品区 - 可能需要添加相应的查询条件
        this.queryParams.roleName = '供应商-普通散户';
      } else if (categoryType === 'guarantor') {
        // 担保商品区 - 筛选担保合作商类型的商品
        this.queryParams.roleName = '供应商-担保合作商';
      } else if (categoryType === 'idle') {
        // 闲置商品区 - 筛选闲置类型商品
        this.queryParams.nature = 'idle';
      } else if (categoryType === 'maintenance') {
        // 检维修商品区 - 筛选检维修类型商品
        this.queryParams.nature = 'maintenance';
      }
    }

    // 先加载基础数据
    Promise.all([this.getTypeTree(), this.getRoleNameList()])
      .then(() => {
        // 获取商品列表数据 (放在基础数据加载后，确保筛选条件已设置)
        return this.getList();
      })
      .then(() => {
        // 基础数据加载完成后，再加载供应商数据
        return this.getSupplierList();
      })
      .then(() => {
        // 使用更长的延迟，避免浏览器自动聚焦
        setTimeout(() => {
          this.isDataLoaded = true;
          this.preventAutoRender = false;
          // 设置搜索框焦点
          this.$nextTick(() => {
            const searchInput = this.$el.querySelector('input[tabindex="1"]');
            if (searchInput) {
              searchInput.focus();
            }
          });
        }, 300);
      })
      .catch(error => console.error('初始化数据加载失败', error))
      .finally(() => {
        this.loading = false;
      });
  },
  mounted() {
    // 防止浏览器自动聚焦下拉框
    document.addEventListener('focusin', this.preventAutoFocus);

    // 阻止所有下拉框的自动展开
    this.preventDropdownAutoExpand();

    // 添加点击外部关闭下拉框的事件监听
    document.addEventListener('click', this.handleOutsideClick);

    // 监听窗口大小变化，更新下拉框位置
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    // 移除事件监听
    document.removeEventListener('focusin', this.preventAutoFocus);
    document.removeEventListener('click', this.handleOutsideClick);
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    getList() {
      this.loading = true;
      // 确保查询参数中的status为数字1
      this.queryParams.status = 1;

      // 打印查询参数，帮助调试
      console.log("查询参数:", JSON.stringify(this.queryParams));

      listProdinfo(this.queryParams).then(response => {
        console.log("API返回结果:", response);

        // 检查响应数据有效性
        if (response && response.rows) {
          this.productListList = response.rows;
          this.total = response.total;

          // 为每个商品添加随机库存数量(仅用于展示)
          this.productListList.forEach(item => {
            if (!item.stockQuantity && item.stockQuantity !== 0) {
              item.stockQuantity = Math.floor(Math.random() * 20);
            }
          });
        } else {
          console.error("API响应数据异常:", response);
          this.$message.warning("获取商品数据异常，请稍后再试");
          this.productListList = [];
          this.total = 0;
        }
      }).catch(error => {
        console.error("获取产品列表失败:", error);
        this.$message.error("获取产品列表失败");
        this.productListList = [];
        this.total = 0;
      }).finally(() => {
        this.loading = false;
      });
    },
    // 获取供应商列表
    getSupplierList() {
      return new Promise((resolve, reject) => {
        // 添加备用供应商数据，确保UI始终有数据显示
        const backupSupplierData = [
          { id: 101, name: '安全电气有限公司', role: '首选供应商' },
          { id: 102, name: '联创机械制造厂', role: '战略供应商' },
          { id: 103, name: '恒信电子科技', role: '合格供应商' },
          { id: 104, name: '优康医疗器械', role: '首选供应商' },
          { id: 105, name: '环宇办公用品', role: '合格供应商' }
        ];

        // 先使用备用数据初始化
        this.supplierList = backupSupplierData;

        // 使用正确的请求方法获取真实数据
        request({
          url: '/system/sup_info/typeTree',
          method: 'get',
          timeout: 10000
        }).then(response => {
          if (response.code === 200 && response.data && Array.isArray(response.data)) {
            const apiSuppliers = response.data.map(item => ({
              id: item.id || item.userId,
              name: item.userName || item.name,
              role: item.roleName
            })).filter(item => item.name && item.id);

            if (apiSuppliers.length > 0) {
              this.supplierList = apiSuppliers;
            }
          }
          resolve();
        }).catch(error => {
          console.error('获取供应商列表失败，使用备用数据', error);
          resolve(); // 即使失败也resolve，因为我们已经设置了备用数据
        });
      });
    },
    // 获取商品类型树
    getTypeTree() {
      console.log('调用TypeTree接口获取商品类型');

      // 使用硬编码的商品类型数据，确保有基本数据显示
      const staticTypeData = [
        {
          id: 1,
          name: '备品备件',
          children: [
            { id: 4, name: '工厂自动化' },
            { id: 28, name: '低压配电' },
            { id: 36, name: '气动液压' },
            { id: 65, name: '动力传动' },
            { id: 76, name: '电线电缆' }
          ]
        },
        {
          id: 357,
          name: '办公用品',
          children: [
            { id: 358, name: '文具' },
            { id: 359, name: '办公设备' }
          ]
        },
        {
          id: 373,
          name: '百货个护',
          children: [
            { id: 374, name: '家居装饰' },
            { id: 375, name: '美妆护肤' },
            { id: 376, name: '小家电' },
            { id: 377, name: '个人护理' },
            { id: 378, name: '家用百货' }
          ]
        }
      ];

      // 初始使用静态数据
      this.typeTreeData = staticTypeData;

      // 提取所有类型到列表
      this.extractThirdLevelTypes(this.typeTreeData);

      // 从API获取真实数据
      fetchCategoryTree().then(response => {
        try {
          // 获取API返回的数据
          const rawData = response.data || response;

          // 使用专门的处理函数处理TypeTree格式的数据
          const processedTypeTree = this.processTypeTreeData(rawData);

          // 如果成功处理出数据，则更新本地数据
          if (processedTypeTree && processedTypeTree.length > 0) {
            this.typeTreeData = processedTypeTree;

            // 更新分类列表
            this.extractThirdLevelTypes(this.typeTreeData);
          }
        } catch (error) {
          console.error('处理API返回数据出错:', error);
        }
      }).catch(error => {
        console.error('调用TypeTree API失败:', error);
      });
    },
    /** 从类型树数据中提取所有层级类型 */
    extractThirdLevelTypes(treeData) {
      this.thirdLevelTypes = [];

      if (!treeData || treeData.length === 0) return;

      // 递归提取所有层级的类型
      const extractAllLevels = (nodes, parentPath = '') => {
        if (!nodes || !Array.isArray(nodes)) return;

        nodes.forEach(node => {
          if (!node) return;

          const id = typeof node.id === 'string' ? parseInt(node.id, 10) : (node.id || 0);
          const name = node.name || node.label || '未命名类型';
          const fullPath = parentPath ? `${parentPath} > ${name}` : name;

          // 添加当前节点到类型列表
          this.thirdLevelTypes.push({
            id: id,
            name: name,
            fullPath: fullPath
          });

          // 递归处理子节点
          if (node.children && node.children.length > 0) {
            extractAllLevels(node.children, fullPath);
          }
        });
      };

      // 开始递归处理
      extractAllLevels(treeData);

      // 确保至少有一条数据
      if (this.thirdLevelTypes.length === 0) {
        this.thirdLevelTypes.push({
          id: 0,
          name: '默认类型',
          fullPath: '默认类型'
        });
      }
    },
    /** 处理类型树数据，确保结构正确 */
    processTypeTreeData(rawData) {
      // 检查数据是否有效
      if (!rawData || !Array.isArray(rawData) || rawData.length === 0) {
        return null;
      }

      // 创建处理结果数组 - 存储一级类目
      let processedData = [];

      // 遍历每一个一级类目项
      rawData.forEach(item => {
        if (!item || !item.firstCatalog) return;

        // 获取一级类目信息
        const firstCatalog = item.firstCatalog;

        // 创建一级类目节点
        const level1Node = {
          id: firstCatalog.id,
          name: firstCatalog.name,
          children: []
        };

        // 处理二级类目 - 来自childrenCatalog数组
        if (item.childrenCatalog && Array.isArray(item.childrenCatalog)) {
          // 只处理与当前一级类目关联的二级类目
          const level2Items = item.childrenCatalog.filter(l2 =>
            l2.parentId === firstCatalog.id ||
            l2.level === 2
          );

          level2Items.forEach(level2Item => {
            // 创建二级类目节点
            const level2Node = {
              id: level2Item.id,
              name: level2Item.name,
              children: []
            };

            // 处理三级类目 - 通常在二级类目的children中
            if (level2Item.children && Array.isArray(level2Item.children)) {
              // 筛选出确实是三级的项目
              const level3Items = level2Item.children.filter(l3 =>
                l3.parentId === level2Item.id ||
                l3.level === 3
              );

              level3Items.forEach(level3Item => {
                // 添加三级类目节点
                level2Node.children.push({
                  id: level3Item.id,
                  name: level3Item.name
                });
              });
            }

            // 只有当有三级节点时才保留children属性
            if (level2Node.children.length === 0) {
              delete level2Node.children;
            }

            // 添加二级节点到一级节点的children中
            level1Node.children.push(level2Node);
          });
        }

        // 只有当有二级节点时才保留children属性
        if (level1Node.children.length === 0) {
          delete level1Node.children;
        }

        // 添加一级节点到结果数组
        processedData.push(level1Node);
      });

      return processedData.length > 0 ? processedData : null;
    },
    /** 根据类型ID获取类型名称 */
    getTypeName(typeId) {
      if (typeId === undefined || typeId === null) return '未知类型';

      // 转换ID类型，便于多种匹配方式
      const typeStr = String(typeId);
      let typeNum = Number(typeId);
      if (isNaN(typeNum)) typeNum = 0;

      // 尝试在提取的类型列表中查找
      const matchingType = this.thirdLevelTypes.find(t =>
        t.id === typeId ||             // 完全匹配
        t.id === typeNum ||            // 数字类型匹配
        String(t.id) === typeStr       // 字符串匹配
      );

      // 如果找到匹配，返回类型名称
      if (matchingType) {
        return matchingType.name;
      }

      // 尝试从旧的字典中查找
      const found = this.dict.type.product_type.find(d => d.value === typeId || d.value === typeStr);
      if (found) return found.label;

      // 如果仍找不到，返回ID信息
      return `类型(${typeId})`;
    },

    // 获取商品类型名称（旧方法，保留兼容）
    getProductTypeName(typeValue) {
      return this.getTypeName(typeValue);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 手动重置各个字段
      this.queryParams.supplierId = undefined;
      this.queryParams.supplierName = null;
      this.queryParams.name = null;
      this.queryParams.roleName = null;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    viewProduct(item) {
      // 使用 Vue Router 跳转到商品详情页面
      this.$router.push({name: 'ProductDetail', params: {productId: item.id}});
    },
    // 处理分页变化
    handlePagination(val) {
      this.queryParams.pageNum = val.page;
      this.queryParams.pageSize = val.limit;
      this.getList();
    },
    // 处理供应商选择变更
    handleSupplierChange(value) {
      if (value) {
        const supplier = this.supplierList.find(item => item.id === value);
        if (supplier) {
          this.queryParams.supplierName = supplier.name;
          this.queryParams.supplierId = value;
        }
      } else {
        this.queryParams.supplierName = null;
        this.queryParams.supplierId = null;
      }
    },
    isCurrentUserSupplier(item) {
      return item.supplierId === this.$store.getters.userId;
    },
    addToCart(item) {
      if (this.isCurrentUserSupplier(item)) {
        this.$message.warning('无法购买自己的商品');
        return;
      }
      this.cartItem = item;
      this.showCart = true;
    },

    // 获取商品图片
    getProductImage(item) {
      // 首先尝试获取商品的第一张图片URL
      if (item.imageUrl) {
        // 如果直接有imageUrl字段，使用该字段
        return item.imageUrl;
      } else if (item.imageList && item.imageList.length > 0) {
        // 如果有imageList字段且不为空数组，使用第一张图片
        return item.imageList[0];
      } else if (typeof item.images === 'string' && item.images) {
        // 如果有images字段且是字符串，可能是逗号分隔的多个URL，取第一个
        const urls = item.images.split(',');
        return urls[0] || defaultImage;
      }

      // 如果没有图片信息，返回默认图片
      return defaultImage;
    },
    // 格式化价格显示
    formatPrice(price) {
      if (!price && price !== 0) return '0.00';

      try {
        // 转换为数字并保留两位小数
        const numPrice = Number(price);
        if (isNaN(numPrice)) return '0.00';
        return numPrice.toFixed(2);
      } catch (e) {
        console.error('价格格式化出错', e);
        return '0.00';
      }
    },
    handleSupplierFocus() {
      // 只有非自动渲染状态才加载数据
      if (!this.preventAutoRender && this.supplierList.length === 0) {
        this.getSupplierList();
      }
    },
    // 防止自动聚焦下拉框
    preventAutoFocus(event) {
      if (this.preventAutoRender) {
        const target = event.target;
        if (target && target.tagName === 'INPUT') {
          // 阻止任何输入框的自动聚焦
          if (target.className.includes('el-select') ||
              target.className.includes('el-cascader') ||
              target.className.includes('dropdown')) {
            event.preventDefault();
            event.stopPropagation();
            target.blur();
          }
        }
      }
    },
    // 阻止下拉框自动展开
    preventDropdownAutoExpand() {
      // 覆盖Element UI默认行为
      const overrideDropdown = () => {
        if (this.$el) {
          const selects = this.$el.querySelectorAll('.el-select');
          selects.forEach(select => {
            const input = select.querySelector('input');
            if (input) {
              // 覆盖原生focus事件
              const originalFocus = input.focus;
              input.focus = function() {
                if (!this.preventAutoRender) {
                  originalFocus.apply(this, arguments);
                }
              };
            }
          });
        }
      };

      // 在下一个事件循环执行
      this.$nextTick(overrideDropdown);
    },
    // 切换供应商下拉框显示状态
    toggleSupplierDropdown() {
      if (!this.showSupplierDropdown && this.supplierList.length === 0) {
        this.loadingSuppliers = true;
        this.getSupplierList().then(() => {
          this.loadingSuppliers = false;
        });
      }

      this.showSupplierDropdown = !this.showSupplierDropdown;

      if (this.showSupplierDropdown) {
        this.$nextTick(() => {
          this.updateDropdownPosition();
        });
      }
    },

    // 更新下拉框位置和宽度
    updateDropdownPosition() {
      const selectEl = this.$refs.supplierSelect;
      if (!selectEl) return;

      const rect = selectEl.getBoundingClientRect();
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
      const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;

      // 计算下拉框位置
      this.dropdownStyle = {
        position: 'fixed',
        top: `${rect.bottom + 5}px`,
        left: `${rect.left}px`,
        minWidth: `${rect.width}px`,
        maxHeight: '300px',
        zIndex: 2000
      };
    },

    // 选择供应商
    selectSupplier(supplier) {
      this.queryParams.supplierId = supplier.id;
      this.queryParams.supplierName = supplier.name;
      this.showSupplierDropdown = false;
      this.handleSupplierChange(supplier.id);
    },

    // 获取选中的供应商名称
    getSelectedSupplierName() {
      if (!this.queryParams.supplierId) return '';
      const supplier = this.supplierList.find(item => item.id === this.queryParams.supplierId);
      return supplier ? supplier.name : '';
    },

    // 点击外部时关闭下拉框
    handleOutsideClick(event) {
      if (this.showSupplierDropdown) {
        const selectEl = this.$refs.supplierSelect;
        const dropdownEl = document.querySelector('.custom-options');

        if (selectEl && dropdownEl &&
            !selectEl.contains(event.target) &&
            !dropdownEl.contains(event.target)) {
          this.showSupplierDropdown = false;
        }
      }

      // 同样处理供应商类型下拉框
      if (this.showRoleNameDropdown) {
        const roleNameSelectEl = this.$refs.roleNameSelect;
        const roleNameDropdownEl = document.querySelectorAll('.custom-options')[1]; // 获取第二个下拉框

        if (roleNameSelectEl && roleNameDropdownEl &&
            !roleNameSelectEl.contains(event.target) &&
            !roleNameDropdownEl.contains(event.target)) {
          this.showRoleNameDropdown = false;
        }
      }
    },
    // 清空选中的供应商
    clearSupplier(event) {
      this.queryParams.supplierId = undefined;
      this.queryParams.supplierName = null;
      this.handleSupplierChange(undefined);
    },
    // 监听窗口大小变化，更新下拉框位置
    handleResize() {
      if (this.showSupplierDropdown) {
        this.updateDropdownPosition();
      }

      if (this.showRoleNameDropdown) {
        this.updateRoleNameDropdownPosition();
      }
    },
    // 获取供应商类型列表
    getRoleNameList() {
      return new Promise((resolve) => {
        request({
          url: '/supply/prodinfo/roleNameList',
          method: 'get'
        }).then(response => {
          if (response.data && Array.isArray(response.data)) {
            this.roleNameList = response.data.map(item => {
              return {
                value: item,
                label: item
              };
            });
          }
          resolve();
        }).catch(error => {
          console.error('获取供应商类型列表失败:', error);
          this.$message.error('获取供应商类型列表失败');
          resolve(); // 即使失败也resolve，因为我们已经有了默认数据
        });
      });
    },
    // 切换供应商类型下拉框显示状态
    toggleRoleNameDropdown() {
      this.showRoleNameDropdown = !this.showRoleNameDropdown;

      if (this.showRoleNameDropdown) {
        this.$nextTick(() => {
          this.updateRoleNameDropdownPosition();
        });
      }
    },
    // 选择供应商类型
    selectRoleName(item) {
      this.queryParams.roleName = item.value;
      this.showRoleNameDropdown = false;
    },
    // 获取选中的供应商类型名称
    getSelectedRoleName() {
      if (!this.queryParams.roleName) return '';
      const role = this.roleNameList.find(item => item.value === this.queryParams.roleName);
      return role ? role.label : '';
    },
    // 清空选中的供应商类型
    clearRoleName() {
      this.queryParams.roleName = null;
      this.showRoleNameDropdown = false;
    },
    // 更新供应商类型下拉框位置
    updateRoleNameDropdownPosition() {
      const selectEl = this.$refs.roleNameSelect;
      if (!selectEl) return;

      const rect = selectEl.getBoundingClientRect();

      // 计算下拉框位置
      this.roleNameDropdownStyle = {
        position: 'fixed',
        top: `${rect.bottom + 5}px`,
        left: `${rect.left}px`,
        minWidth: `${rect.width}px`,
        maxHeight: '300px',
        zIndex: 2000
      };
    },
    // 获取类别名称
    getCategoryTypeName(type) {
      const typeMap = {
        'strategic': '战略商品区',
        'selfOperated': '自营商品区',
        'guarantor': '担保商品区',
        'idle': '闲置商品区',
        'maintenance': '检维修商品区'
      };
      return typeMap[type] || type;
    },
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);

  /* 自定义下拉框样式 */
  .custom-select-wrapper {
    position: relative;
    width: 100%;
    font-size: 14px;

    .custom-select {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 32px;
      padding: 0 12px;
      background-color: #fff;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.2s;

      &:hover {
        border-color: #c0c4cc;
      }

      .selected-value {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #606266;
      }

      .clear-icon {
        font-size: 12px;
        color: #c0c4cc;
        margin-right: 8px;

        &:hover {
          color: #909399;
        }
      }

      i.el-icon-arrow-down {
        margin-left: 8px;
        color: #c0c4cc;
        transition: transform 0.3s;

        &.is-open {
          transform: rotate(180deg);
        }
      }
    }
  }

  /* 级联选择器样式 */
  ::v-deep .el-cascader {
    width: 100% !important;

    .el-input__inner {
      height: 32px;
      line-height: 32px;
      padding-right: 30px;
    }

    .el-input__suffix {
      right: 5px;
      top: 1px;
      pointer-events: auto;
    }

    .el-cascader__dropdown {
      z-index: 3000 !important; /* 确保级联下拉框在最顶层 */
    }
  }

  /* 供应商类型下拉框样式 */
  ::v-deep .el-select {
    width: 100% !important;

    .el-input__inner {
      height: 32px;
      line-height: 32px;
    }
  }

  /* 确保下拉菜单可见 */
  ::v-deep .el-select-dropdown, ::v-deep .el-cascader-menus {
    z-index: 3000 !important;
    visibility: visible !important;
    display: block !important;
    position: absolute !important;
    opacity: 1 !important;
  }

  /* 确保下拉菜单的项目可点击 */
  ::v-deep .el-cascader-menu__item {
    padding: 8px 20px;
    position: relative;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #606266;
    height: 34px;
    line-height: 34px;
    box-sizing: border-box;
    cursor: pointer;
    outline: none;

    &:hover {
      background-color: #f5f7fa;
    }

    &.is-active {
      color: #409EFF;
      font-weight: 700;
    }
  }

  .page-header {
    margin-bottom: 20px;

    .header-title {
      display: flex;
      align-items: center;
      font-size: 20px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 8px;

      i {
        color: #409EFF;
        margin-right: 10px;
        font-size: 24px;
      }
    }

    .header-desc {
      color: #606266;
      font-size: 14px;
    }
  }

  .search-card {
    margin-bottom: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  }

  .product-list-card {
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      span {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }

      .header-actions {
        .el-button {
          color: #606266;

          i.el-icon--right {
            margin-left: 5px;
          }
        }
      }
    }
  }

  .products-container {
    .product-col {
      margin-bottom: 20px;

      .product-card {
        height: 100%;
        transition: all 0.3s;
        border-radius: 6px;
        overflow: hidden;
        cursor: pointer;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        background-color: #fff;
        border: 1px solid #ebeef5;

        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
        }

        .product-image {
          height: 160px;
          overflow: hidden;
          position: relative; /* 设置为相对定位，为绝对定位的子元素提供定位上下文 */
        }

        .product-image img {
          width: 100%;
          height: 100%;
          object-fit: cover; /* 保证图片覆盖整个容器 */
          transition: transform 0.6s; /* 添加过渡效果，使图片缩放时有动画效果 */
        }

        .product-image:hover img {
          transform: scale(1.05); /* 鼠标悬停时图片放大 */
        }

        .product-image .product-tags {
          position: absolute; /* 设置为绝对定位，使其脱离文档流 */
          top: 8px; /* 距离容器顶部8像素 */
          right: 8px; /* 距离容器右侧8像素 */
          z-index: 2; /* 确保标签在图片上方显示 */
        }

        .product-info {
          padding: 12px;
          background: #fff;

          .product-title {
            font-size: 14px;
            margin-bottom: 8px;
            line-height: 1.4;
            height: 40px;
            overflow: hidden;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            color: #303133;
            font-weight: 500;
          }

          .product-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin-bottom: 10px;
            font-size: 12px;
            overflow: hidden;
            height: 26px;

            .product-type, .product-supplier {
              color: #909399;
              background: #f5f7fa;
              padding: 2px 6px;
              border-radius: 3px;
              display: inline-block;
              max-width: 45%;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              transition: all 0.15s ease-out;
              cursor: pointer;

              &:hover {
                background: #ecf5ff;
                color: #409EFF;
                box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
                transform: translateY(-1px);
              }
            }
          }

          .bottom-info {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .product-price {
              color: #f56c6c;
              font-size: 16px;
              font-weight: bold;
            }
          }
        }
      }
    }

    .empty-block {
      padding: 40px 0;
      text-align: center;
      color: #909399;

      i {
        font-size: 48px;
        margin-bottom: 15px;
        display: block;
      }

      span {
        display: block;
        margin-bottom: 15px;
      }
    }
  }

  .pagination-container {
    text-align: right;
    padding-top: 20px;
  }
}

@media screen and (max-width: 1200px) {
  .products-container .product-col {
    width: 25%;
  }
}

@media screen and (max-width: 992px) {
  .products-container .product-col {
    width: 33.33%;
  }
}

@media screen and (max-width: 768px) {
  .products-container .product-col {
    width: 50%;
    padding: 0 8px;
    margin-bottom: 16px;
  }

  .app-container {
    padding: 15px;
  }

  .products-containers .product-card .product-image {
    height: 140px;
  }
}

@media screen and (max-width: 480px) {
  .products-container .product-col {
    width: 100%;
    padding: 0 5px;
    margin-bottom: 15px;
  }
}
</style>

<style lang="scss">
/* 防止下拉框自动展开 */
.el-select-dropdown.el-popper {
  display: none;
}
.el-select-dropdown.el-popper[style*="display: block"] {
  display: block !important;
}
/* 确保供应商类型下拉框能正常显示 */
.el-select.el-select--small .el-select-dropdown.el-popper[style*="display: block"] {
  display: block !important;
  z-index: 3001 !important;
  visibility: visible !important;
  opacity: 1 !important;
}

/* 顶层下拉框样式 */
.custom-options {
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;

  .custom-options-wrapper {
    overflow-y: auto;
    max-height: 300px;

    .custom-option {
      padding: 8px 12px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      cursor: pointer;
      font-size: 14px;

      &:hover {
        background-color: #f5f7fa;
      }

      &.is-selected {
        color: #409EFF;
        font-weight: bold;
        background-color: #f0f7ff;
      }

      .option-role {
        color: #8492a6;
        font-size: 13px;
        margin-left: 8px;
      }
    }

    .no-data {
      padding: 10px 0;
      text-align: center;
      color: #909399;
      font-size: 14px;
    }
  }
}
</style>

<style lang="scss">
.category-tag {
  display: inline-block;
  margin-left: 10px;
  background-color: #f0f9eb;
  color: #67c23a;
  padding: 2px 8px;
  font-size: 14px;
  border-radius: 4px;
}
</style>

